use actix::prelude::*;
use crate::action::recovery_list_action;
use crate::service::recovery_list_service;
use crate::DbPool;
use crate::ip_block;

use std::time::Duration;
use crossbeam_channel::tick;



// Define actor
pub struct TimeoutScheduler {
    pool: DbPool,
    ip_block: ip_block::Iptables,
}

// Provide Actor implementation for our actor
impl Actor for TimeoutScheduler {
    type Context = Context<Self>;

    fn started(&mut self, _ctx: &mut Self::Context) {
        println!("TimeoutScheduler Actor is started");
        let arbiter = Arbiter::new();
        arbiter.spawn(TimeoutScheduler::execute(self.pool.clone(), self.ip_block.clone()));
    }

    fn stopped(&mut self, _ctx: &mut Context<Self>) {
        println!("TimeoutScheduler Actor is stopped");
    }
}


impl TimeoutScheduler {

    pub(crate) fn get_scheduler(pool: DbPool, ip_block: ip_block::Iptables) -> Self {
        TimeoutScheduler { pool, ip_block }
    }

    async fn execute(pool: DbPool, ip_block: ip_block::Iptables) {

        let conn = pool.get().unwrap();

        let ticker = tick(Duration::from_millis(1000 * 10));
        loop {

            // 查询过期记录
            let list_result = recovery_list_action::find_expired(1, 100, &conn);

            if list_result.is_ok() {
                let list_tuple = list_result.unwrap();
                let list_op = list_tuple.0;
                if list_op.is_some() {
                    let list = list_op.unwrap();
                    for recovery_list in list {
                        let recovery_result = recovery_list_service::do_recovery(&recovery_list, &ip_block, &conn);
                        println!("{:?}", recovery_result);
                    }
                }   
            }

            let _ = ticker.recv().unwrap();

        }
    }

}